﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using WebApplication2.Model;
using WebApplication2.Server;
using WebApplication2.Util;

namespace WebApplication2.Handler
{
    /// <summary>
    /// FileHandler 的摘要说明
    /// </summary>
    public class FileHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string funC = context.Request["func"];
            try
            {
                switch (funC)
                {
                    case "update":
                        update(context);
                        break;
                    case "getURL":
                        getURL(context);
                        break;
                    case "delete":
                        deletePic(context);
                        break;
                    case "year":
                        year(context);
                        break;
                    default:
                        context.Response.Write("{data:\"参数错误！\"}");
                        Console.WriteLine("傻逼,参数错误！");
                        break;
                }
            }
            catch (Exception e)
            {
                context.Response.ClearContent();
                context.Response.Write(e.ToString());
            }


        }



        public void update(HttpContext context)
        {
            string msg = string.Empty;
            string error = string.Empty;
            string result = string.Empty;
            string filePath = string.Empty;
            string fileNewName = string.Empty;
            string projectName = context.Request["name"];
            string projectid = context.Request["project_id"];
            int code = 0;
            string json = "";
            //这里只能用<input type="file" />才能有效果,因为服务器控件是HttpInputFile类型
            HttpFileCollection files = context.Request.Files;
            if (files.Count > 0)
            {
                //设置文件名
                fileNewName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "_" + System.IO.Path.GetFileName(files[0].FileName);
                //保存文件名和路径到数据库
                files[0].SaveAs(context.Server.MapPath("~/Upload/" + fileNewName));
                string sql = "insert into T_File  (F_FileName,F_Path,F_ProjectName,F_Time,F_ProjectID) Values('" + fileNewName + "','~/Upload/" + fileNewName + "','" + projectName + "','" + DateTime.Now + "','" + projectid + "')";
                code = MrDBAccess.ExecuteNonQuery(sql);
                msg = "文件上传成功！";
                ////应该写一些返回信息的
                //MyFlieModel file = new MyFlieModel();
                //List<MyFlieModel> MyfileModels = new List<MyFlieModel>();
                result = "{msg:'" + msg + "',filenewname:'" + fileNewName + "'}";
                code = 1;
            }
            else
            {
                error = "文件上传失败！";
                result = "{ error:'" + error + "'}";
            }
            //context.Response.Write(result);
            //context.Response.End();
            json = "{\"Code\":\"" + code + "\",\"Msg\":\"" + msg + "\"}";
            context.Response.Write(json);
        }

        public void getURL(HttpContext context)
        {
            int code = 0;
            string sql;
            string json = "";
            string pro_ID = context.Request["project_id"];
            List<MyFlieModel> list = new List<MyFlieModel>();
            FeedBackMsg<List<MyFlieModel>> feedBack = new FeedBackMsg<List<MyFlieModel>>();
            sql = "select * from T_File WHERE F_ProjectID='" + pro_ID + "'";
            DataRowCollection rows = MrDBAccess.ExecuteDataSet(sql).Tables[0].Rows;
            if (rows != null && rows.Count > 0)
            {
                int iRowLength = rows.Count;
                for (int i = 0; i < iRowLength; i++)
                {
                    MyFlieModel file = new MyFlieModel();
                    file.FileName = DataBase.ObjectToString(rows[i]["F_FileName"]);
                    list.Add(file);
                }

            }
            feedBack.Code = 1;
            feedBack.Msg = "返回一些图片的文件名，再拼接成URL";
            feedBack.Obj = list;
            json = ObjToJson.ToJson(feedBack);
            context.Response.Write(json);
        }

        public void year(HttpContext context)
        {
            string json = "";
            //查询返回多条结果，采用泛型集合保存查询结果
            Output output = new Output();
            List<Output> list = new List<Output>();
            //一个List<Output>的feedBack
            FeedBackMsg<List<Output>> feedBack = new FeedBackMsg<List<Output>>();
            string sql = string.Empty;
            int max = Getyear().Max();
            int min = Getyear().Min();
            //逐年循环查询
            for (int i = min - 1; i < max + 2; i++)
            {
                output.Year = i;
                sql = "select * from T_ProjectInfo where YEAR(F_finishe) =" + i + " ";
                DataRowCollection rows = MrDBAccess.ExecuteDataSet(sql).Tables[0].Rows;
                int iRowLength = rows.Count;
                ////对产值Value进行累加
                //if (iRowLength > 0)
                //{
                //    for (int j = 0; j < iRowLength; j++)
                //    {
                //        output.Value = DataBase.ObjectToInt(rows[j]["F_Budge"]) + output.Value;
                //    }
                //}
                list.Add(output);
                //将output置空，循环使用
                //output.Year = 0;
                //output.Value = 0;
            }
            feedBack.Code = 1;
            feedBack.Msg = "年度统计数据";
            feedBack.Obj = list;
            json = ObjToJson.ToJson(feedBack);
            context.Response.Write(json);
        }



        public List<Int32> Getyear()
        {
            List<String> Stryear = new List<string>();
            List<Int32> year = new List<Int32>();
            string sql = string.Empty;
            sql = "SELECT * from T_ProjectInfo";
            DataRowCollection rows = MrDBAccess.ExecuteDataSet(sql).Tables[0].Rows;
            if (rows != null && rows.Count > 0)
            {
                int iRowLength = rows.Count;
                for (int i = 0; i < iRowLength; i++)
                {
                    Stryear.Add(DataBase.ObjectToString(rows[i]["F_Finishe"]));
                }
            }
            foreach (String item in Stryear)
            {
                DateTime time = Convert.ToDateTime(item);
                year.Add(time.Year);
            }

            return year;

        }





        public void deletePic(HttpContext context)
        {


        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}